﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

public partial class UserMan : xIx.Web.UI.PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Button1.DataBind();
            if (string.IsNullOrEmpty(Request["Uid"]))
            {
                InitList();
            }
            else
            {
                InitDetail();
            }
        }

    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        object o = DetailsView1.DataItem;
        Console.WriteLine(o);
    }
    public void InitList()
    {
        MultiView1.ActiveViewIndex = 0;
        UsersTab = ReloadUsersTab();
        GridView1.DataSource = UsersTab;
        GridView1.DataBind();
    }
    public void InitDetail()
    {
        MultiView1.ActiveViewIndex = 1;
        Uid = Request["Uid"];
        UsersTab = ReloadUsersTab();
        if (UsersTab.Rows.Count == 0)
        {
            long i = xIx.Data.DbHelper.StaticGenUid();
            UsersTab.Rows.Add(new object[] { i });
            Uid = i.ToString();
            UsersTab.Rows[0]["isActive"] = false;
            UsersTab.Rows[0]["RoleID"] = "Member"; UsersTab.Rows[0]["GroupID"] = "1";
            IsInsert = true;
        }
        DetailsView1.DataSource = UsersTab;
        UsersTab.PrimaryKey = new DataColumn[] { UsersTab.Columns["ID"] };
        DetailsView1.DataBind();
    }
    public bool IsInsert
    {
        get
        {
            object v = ViewState["IsInsert"];
            if (null != v)
            {
                return (bool)v;
            }
            else
            {
                return default(bool);
            }
        }
        set
        {
            ViewState["IsInsert"] = value;
        }
    }
    public string Uid
    {
        get
        {
            object v = ViewState["Uid"];
            if (null != v)
            {
                return (string)v;
            }
            else
            {
                return default(string);
            }
        }
        set
        {
            ViewState["Uid"] = value;
        }
    }

    public DataTable ReloadUsersTab()
    {
        using (xIx.Data.DbHelper dh = new xIx.Data.DbHelper())
        {
            string uid = Uid;
            if (string.IsNullOrEmpty(uid))
            {
                return dh.Table["Sys_Users"].Where("ID!='Admin'").Select();
            }
            else
            {
                return dh.Table["Sys_Users"].Where("ID=@id").Select("id", uid);
            }
        }
    }

    public DataTable UsersTab
    {
        get
        {
            DataTable dt = Page.Cache["UsersTab"] as DataTable;
            if (null == dt)
            {
                dt = ReloadUsersTab();
                UsersTab = dt;
            }
            return dt;
        }
        set
        {
            Page.Cache["UsersTab"] = value;
        }
    }

    protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        DataRow dr = UsersTab.Rows[0];

        SortedList<string, object> sl = new SortedList<string, object>();

        if (IsInsert)
        {
            sl.Add("ID", dr["ID"]);
            sl.Add("regreqtime", DateTime.Now);
            sl.Add("isregaudit", true);
            sl.Add("regaudtime", DateTime.Now);

        }
        else
        {
            if (!(bool)dr["isregaudit"])
            {
                sl.Add("isregaudit", true);
                sl.Add("regaudtime", DateTime.Now);
            }
        }


        //检查每个字段，如果修改了则加入列表，我只处理的部分，要补全。
        //"Name,Title,Pwd,Province,addr,email,telephone,cellphone,lastaccess,descript"
        //RoleId
        //RoleIds
        //isactive
        //regreqtime
        //regaudtime


        ITextControl tb = null;
        CheckBox cb = null;

        int[] ria = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 14, 15 };
        string[] rna = "Name,Title,Pwd,Province,addr,email,telephone,cellphone,descript,RoleID,GroupID".Split(',');

        for (int i = 0; i < ria.Length; i++)
        {
            //tb = (DetailsView1.Rows[ria[i]].Cells[1].Controls[0] as ITextControl);
            tb =Utils.FindControl<ITextControl>(DetailsView1.Rows[ria[i]].Cells[1],0);
            if (tb.Text != dr[rna[i]].ToString()) sl.Add(rna[i], tb.Text);
        }

        if (rna[0].Trim() == string.Empty || rna[1].Trim() == string.Empty || rna[2].Trim() == string.Empty || rna[2].Trim().Length<3)
        {
            Alert("请填写所有必填项。密码必须三位以上。");
            e.Cancel = true;
            return;
        }

        cb = (DetailsView1.Rows[9].Cells[1].Controls[0] as CheckBox);
        if (IsInsert || cb.Checked != (bool)dr["isactive"]) sl.Add("isactive", cb.Checked);

        if (sl.Count > 0)
        {
            using (xIx.Data.DbHelper dh = new xIx.Data.DbHelper())
            {
                List<string> fl = new List<string>(); fl.AddRange(sl.Keys);
                List<object> vl = new List<object>(); vl.AddRange(sl.Values);

                int r = -1;
                if (IsInsert)
                {
                    r = dh.Table["Sys_Users"].Fields(fl.ToArray()).InsertWith(vl.ToArray()).Exec();
                }
                else
                {
                    r = dh.Table["Sys_Users"].Fields(fl.ToArray()).UpdateWith(vl.ToArray()).Where("ID=@id").Exec(dr["ID"]);
                }
                Alert("操作" + (r == 1 ? "成功" : "失败。"));
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Rp", "window.opener.document.getElementById('" + Request["Rp"] + "').click();", true);

            }
        }

        UsersTab = ReloadUsersTab();
        if (UsersTab.Rows.Count == 0)
        {
            long i = xIx.Data.DbHelper.StaticGenUid();
            UsersTab.Rows.Add(new object[] { i });
            Uid = i.ToString();
            UsersTab.Rows[0]["isActive"] = false;
            IsInsert = true;
        }
        else
        {
            IsInsert = false;
        }
        DetailsView1.DataSource = UsersTab;
        DetailsView1.DataBind();

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (e.RowIndex > -1 && e.RowIndex < UsersTab.Rows.Count)
        {
            int c = 0;
            using (xIx.Data.DbHelper dh = new xIx.Data.DbHelper())
            {
                c = dh.Table["Sys_Users"].Where("ID=@id").Delete(UsersTab.Rows[e.RowIndex]["ID"]);
                Alert("操作" + (c == 1 ? "成功" : "失败。"));
            }
            if (c == 1)
            {
                UsersTab = ReloadUsersTab();
                GridView1.DataSource = UsersTab;
                GridView1.DataBind();
            }
        }
    }
    protected void Button2_Click1(object sender, EventArgs e)
    {
        UsersTab = ReloadUsersTab();
        GridView1.DataSource = UsersTab;
        GridView1.DataBind();
    }
}
